package com.sneaker.shower.util;

import com.sneaker.shower.entity.dto.map.DistanceRespDTO;
import com.sneaker.shower.entity.dto.map.GeoCodeRespDTO;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Hechangjian
 * @version 1.0
 * @className MapUtil
 * @date 2019/05/18 17:00
 * @description 高德地图apiUtil
 * @program holder-saas-store
 */
@Component
@Slf4j
public class MapUtils {
    private static final String GEO_URL = "https://restapi.amap.com/v3/geocode/geo";
    private static final String DISTANT_URL = "https://restapi.amap.com/v3/distance";
    @Value("${map.key}")
    private String key;

    /**
     * 通过地址名称获取地址详细信息
     *
     * @param address
     * @return
     */
    public GeoCodeRespDTO geoLocation(String address) {
        Map<String, Object> params = new HashMap<>();
        params.put("key", key);
        params.put("address", address);
        String result = HttpsClientUtils.doGet(GEO_URL, params);
        try {
            GeoCodeRespDTO geoCodeRespDTO = JacksonUtils.toObject(GeoCodeRespDTO.class, result);
            return geoCodeRespDTO;
        } catch (Exception e) {
            log.info("Json转换异常， result ：{}", result);
            throw new RuntimeException("系统异常");
        }
    }

    /**
     * 计算两位置距离，传入经纬度
     *
     * @param lonA A坐标经度
     * @param latA A坐标维度
     * @param lonB B坐标经度
     * @param latB B坐标维度
     * @return 距离（单位：米）
     */
    public Integer distant(BigDecimal lonA, BigDecimal latA, BigDecimal lonB, BigDecimal latB) {
        Map<String, Object> params = new HashMap<>();
        params.put("key", key);
        params.put("origins", lonA + "," + latA);
        params.put("destination", lonB + "," + latB);
        params.put("type", 0);
        params.put("output", "JSON");
        String result = HttpsClientUtils.doGet(DISTANT_URL, params);
        try {
            DistanceRespDTO distanceRespDTO = JacksonUtils.toObject(DistanceRespDTO.class, result);
            return Integer.parseInt(Objects.requireNonNull(distanceRespDTO).getDistantDTOList().get(0).getDistance());
        } catch (Exception e) {
            log.info("距离计算Json 转换异常， result : {}", result);
            log.info("error:" + e.getCause());
            throw new RuntimeException("高德地图API调用异常");
        }
    }

    /**
     * 经纬度处理
     *
     * @param location location
     * @return return
     */
    public Pair<BigDecimal, BigDecimal> splitLocation(String location) {
        if (StringUtils.isEmpty(location))
            return null;
        String[] split = location.split(",");
        if (split.length != 2)
            return null;
        return new Pair<>(new BigDecimal(split[0]), new BigDecimal(split[1]));
    }

}
